package org.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;

import lombok.AllArgsConstructor;

import org.example.bean.Orders;

import org.example.service.MessageService;
import org.example.service.OrdersService;

import org.example.util.AlipayUtil;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


/**
 * 支付宝接口，
 //支付宝沙箱接口
 */

@RestController
@AllArgsConstructor
@RequestMapping("/api/alipay")
public class AliPayController {

    @Autowired
    private AlipayUtil alipayUtil;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private MessageService messageService;

    @PostMapping(value = "/pay")  //一般使用GetMapping 如果参数URL过长，使用PostMapping
    @ResponseBody
    public Map<String, String> alipay(@RequestBody Orders orders) throws AlipayApiException {
        // 调用支付宝接口获取支付表单
        String form = alipayUtil.sendRequestToAlipay(
                String.valueOf(orders.getOrder_id()),
                orders.getTotal_price(),
                "商品支付"
        );

        // 从表单中提取支付URL
        String payUrl = extractPayUrl(form);

        return Map.of(
                "payUrl", payUrl,
                "form", form
        );
    }

    private String extractPayUrl(String form) {
        // 简单解析HTML表单获取action URL
        int start = form.indexOf("action=\"") + 8;
        int end = form.indexOf("\"", start);
        return form.substring(start, end);
    }

    @PostMapping("/toSuccess") //异步回调必须支持POST请求 //打开内网穿透
    public String paySuccess(@RequestParam Map<String, String> params) {
        String orderId = params.get("out_trade_no");
        String query = alipayUtil.query(orderId);

        JSONObject jsonObject = JSONObject.parseObject(query);
        Object response = jsonObject.get("alipay_trade_query_response");
        Map map = (Map)response;
        Object status = map.get("trade_status");
        //1.验证签名
        if("TRADE_SUCCESS".equals(status.toString())) {
            // 2.更新订单状态
            //0-已下单，1-待发货, 2-已发货,3-已完成
            ordersService.updateOrderStatus(Integer.parseInt(orderId), 1);

            //3.发送消息到消息队列
            messageService.sendMessage(orderId);

            return "redirect:http://localhost:8080/#/send";
        } else {
            return "redirect:http://localhost:8080/#/cart";
        }
    }
}